<template>
  <div class="app-main-container">
    <QueryForm
      v-model="filters"
      :query-form-config="queryFormConfig"
      @handleQuery="getList(1)"
      @clear="clearFilters"
    />
    <div v-if="meta.indexOf('AccountAdd') > -1" class="doumee-table-buttons">
      <el-button v-preventReClick type="primary" @click="toAccountAdd(0)">新增</el-button>
    </div>
    <el-table
      ref="table"
      v-loading="listLoading"
      :data="list"
      border
      fit
      :header-row-class-name="'table-header'"
      class="doumee-element-table"
    >
      <el-table-column
        align="center"
        label="用户人脸"
        width="120"
        show-overflow-tooltip
        prop="faceImg2"
      >
        <template v-if="scope.row.faceImg2" slot-scope="scope">
          <el-image
            fit="contain"
            :src="scope.row.faceImg2"
            :preview-src-list="[scope.row.faceImg2]"
          />
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="登陆账号"
        prop="userName"
        min-width="120"
        show-overflow-tooltip
        fixed="left"
      />
      <el-table-column
        align="center"
        label="用户昵称"
        prop="nickName"
        min-width="120"
        show-overflow-tooltip
        fixed="left"
      />
      <el-table-column
        align="center"
        label="真实姓名"
        prop="realName"
        min-width="120"
        show-overflow-tooltip
        fixed="left"
      />
      <el-table-column
        align="center"
        label="手机号"
        prop="phone"
        show-overflow-tooltip
        min-width="140"
      />
      <el-table-column
        align="center"
        label="关联角色"
        prop="roleList_"
        show-overflow-tooltip
        min-width="200"
      />
      <el-table-column
        align="center"
        label="关联场馆"
        prop="stadiumList_"
        show-overflow-tooltip
        min-width="200"
      />
      <el-table-column
        align="center"
        label="关联小票机"
        prop="printerName"
        show-overflow-tooltip
        min-width="200"
      />
      <el-table-column align="center" label="状态" min-width="120">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            :active-value="'1'"
            :inactive-value="'0'"
            :disabled="meta.indexOf('AccountOnOff') == -1"
            @change="toAccountStatus($event, scope.row.id)"
          />
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="用户说明"
        prop="info"
        min-width="300"
        show-overflow-tooltip
      />
      <el-table-column
        label="操作"
        min-width="300"
        align="center"
        fixed="right"
      >
        <template slot-scope="scope">
          <div class="flex-cc">
            <el-button
              v-if="meta.indexOf('AccountEdit') > -1"
              v-preventReClick
              type="text"
              @click="toAccountAdd(1, scope.row)"
            >编辑</el-button>
            <el-button
              v-if="meta.indexOf('AccountEditRPwd') > -1"
              v-preventReClick
              type="text"
              @click="toAccountRepassword(scope.row)"
            >重置密码</el-button>
            <el-button
              v-if="meta.indexOf('AccountDel') > -1"
              v-preventReClick
              type="text"
              style="color: red"
              @click="toAccountDelete(scope.row.id)"
            >删除</el-button>
            <el-button
              v-preventReClick
              type="text"
              @click="tbry(scope.row.id)"
            >下发设备</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <Pagination
      :total="total"
      :page="pagination.page"
      @current-change="getList"
      @SizeChange="handleSizeChange"
    />

    <!-- 新增 编辑 用户 -->
    <el-dialog
      :close-on-click-modal="modalDialog"
      :lose-on-press-escape="modalDialog"
      :title="addEditType ? '编辑用户' : '新增用户'"
      :visible.sync="showAddAccount"
      width="850px"
      @closed="cancelAddAccount"
    >
      <el-form
        ref="ruleForm"
        :model="formAddAccount"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="用户人脸" prop="faceImg2">
          <transition name="fade">
            <Cropper
              v-if="dialogCropperVisible"
              :option-img="optionImg"
              :fileinfo="fileinfo"
              use-type="USER_IMG"
              :fixed-number="[32, 32]"
              @formSubmit="cropperSubmit"
              @formClose="cropperClose"
            />
          </transition>
          <div class="df_ac">
            <el-upload
              class="device-uploader"
              :action="uploadFileUrl"
              :data="uploadParam"
              :auto-upload="false"
              :show-file-list="false"
              accept=".jpg,.png"
              :on-change="addFileChange"
            >
              <i class="el-icon-plus uploader-icon" />
              <div
                v-show="formAddAccount.faceImg2"
                class="file"
                :style="'background-image: url(' + formAddAccount.faceImg2 + ')'"
              >
                <div class="delete">
                  <i
                    class="el-icon-delete icon"
                    @click.stop="deleteDeviceConfigAddImage"
                  />
                </div>
              </div>
            </el-upload>
            <div class="placeholder9">
              <div>建议尺寸：100px X 100px</div>
              <div>支持png、jpg、jpeg格式，大小不超过2M，上传图片不允许涉及政治敏感与色情</div>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="登陆账号" prop="userName">
          <el-input v-model="formAddAccount.userName" maxlength="20" />
          <div>
            <div v-if="addEditType && formAddAccount.userNameTemp != formAddAccount.userName" class="red fs_12">登录账号修改后，系统将重置用户密码为系统默认密码，详见【配置管理--通用配置--后台用户默认密码】；</div>
            <div v-else class="placeholder9">新建用户初始密码为系统默认密码，详见【配置管理--通用配置--后台用户默认密码】；</div>
          </div>
        </el-form-item>
        <el-form-item label="用户昵称" prop="nickName">
          <el-input v-model="formAddAccount.nickName" maxlength="20" />
        </el-form-item>
        <el-form-item label="真实姓名">
          <el-input v-model="formAddAccount.realName" maxlength="20" />
        </el-form-item>
        <el-form-item label="身份证号">
          <el-input v-model="formAddAccount.identityNumber" maxlength="20" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input
            v-model="formAddAccount.phone"
            type="phone"
            maxlength="11"
          />
        </el-form-item>
        <el-form-item label="关联角色" prop="roleIds">
          <el-select
            v-model="formAddAccount.roleIds"
            value-key="id"
            placeholder="选择角色"
            multiple
            style="width: 100%"
            clearable
          >
            <el-option
              v-for="item in roleListData"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="关联场馆" prop="list">
          <el-checkbox-group v-model="formAddAccount.list">
            <el-checkbox
              v-for="item in venueListData"
              :key="item.id"
              :label="item.id"
              :name="item.id"
            >{{ item.name }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="关联小票机">
          <el-select
            v-model="formAddAccount.printerId"
            placeholder="选择小票机"
            clearable
            style="width: 100%"
          >
            <el-option
              v-for="item in printerListb"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="用户状态">
          <el-switch
            v-model="formAddAccount.status"
            :active-value="'1'"
            :inactive-value="'0'"
          />
        </el-form-item>
        <el-form-item label="用户说明">
          <el-input v-model="formAddAccount.info" />
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="cancelAddAccount">取消</el-button>
        <el-button :loading="subLoading" type="primary" @click="confirmAddAccount">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  uploadFile,
  venueList,
  roleList,
  printerList,
  accountList,
  syncUserToDev,
  accountAdd,
  accountRepassword,
  accountStatus,
  accountEdit,
  accountDelete,
  accountRoleDelete
} from '@/api'
import Cropper from '@/components/cropper'
import { parseTime } from '@/utils'
import Pagination from '@/components/paginations'
import { queryFormConfig } from './config'
export default {
  name: 'AccountList',
  components: {
    Cropper,
    Pagination
  },
  data() {
    return {
      queryFormConfig,
      modalDialog: this.$store.state.app.dialog,
      subLoading: false,
      dialogCropperVisible: false,
      param: {},
      meta: [],
      uploadFileUrl: uploadFile,
      uploadParam: {
        folder: 'USER_IMG'
      },
      cur_page: 1,
      venueListData: [],
      roleListData: [],
      list: [],
      filters: {
        userName: ''
      },
      pagination: {
        firstQueryTime: new Date(),
        page: 1,
        rows: 10
      },
      total: 0,
      addEditType: 0,
      showAddAccount: false,
      imageList: [],
      formAddAccount: {
        userName: '',
        realName: '',
        phone: '',
        roleIds: [],
        list: [],
        status: '1',
        info: ''
      },
      printerListb: [],
      rules: {
        userName: [
          { required: true, message: '请输入登陆账号', trigger: 'blur' }
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        nickName: [
          { required: true, message: '请输入用户昵称', trigger: 'blur' }
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        realName: [
          { required: true, message: '请输入真实姓名', trigger: 'blur' }
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        identityNumber: [
          { required: true, message: '请输入身份证号', trigger: 'blur' },
          {
            required: true,
            pattern:
              /^(([1-9][0-9]{5}(19|20)[0-9]{2}((0[1-9])|(1[0-2]))([0-2][1-9]|10|20|30|31)[0-9]{3}([0-9]|X|x))|([1-9][0-9]{5}[0-9]{2}((0[1-9])|(1[0-2]))([0-2][1-9]|10|20|30|31)[0-9]{3}))$/,
            message: '请输入正确的身份证号',
            trigger: 'blur'
          }
        ],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' }
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        roleIds: [
          {
            type: 'array',
            required: true,
            message: '请选择关联角色',
            trigger: 'change'
          }
        ],
        list: [
          {
            type: 'array',
            required: true,
            message: '请选择关联场馆',
            trigger: 'change'
          }
        ]
      }
    }
  },
  created() {
    this.meta = this.$route.meta.buttons || []
    this.getPrinterList()
    this.getList(1)
    this.getRoleList()
    this.getVenueList()
  },
  mounted() {
    this.$nextTick(() => {
      this.$refs.table.doLayout()
    })
  },
  activated() {
    this.$nextTick(() => {
      this.$refs.table.doLayout()
    })
  },
  methods: {
    getPrinterList() {
      printerList({}).then((res) => {
        if (res.errorCode !== '000000') return
        this.printerListb = res.recordList
      })
    },
    tbry(userId) {
      syncUserToDev({ param: {
        type: '0',
        userType: '0',
        userId
      }}, sessionStorage.getItem('venueId')).then(res => {
        if (res.errorCode === '000000') {
          this.$message.success('同步成功')
        }
      }).catch(err => {
        console.log(err)
      })
    },
    // 上传成功
    uploadSuccess(response, file, fileList) {
      if (response.success) {
        this.$set(this.formAddAccount, 'faceImg2', response.showUrl)
        this.$set(this.formAddAccount, 'faceImg', response.insertUrl)
        this.$refs.ruleForm.clearValidate()
      } else {
        this.$message.error(response.msg || '上传失败')
      }
    },
    // 裁剪确定按钮
    cropperSubmit(config) {
      // preImg 完整路径  urlPre 不包含域名
      if (config.success) {
        this.$set(this.formAddAccount, 'faceImg2', config.showUrl)
        this.$set(this.formAddAccount, 'faceImg', config.insertUrl)
        this.$refs.ruleForm.clearValidate()
        this.dialogCropperVisible = false
      } else {
        this.$message.error(config.msg || '上传失败')
        this.$refs.ruleForm.clearValidate()
        this.dialogCropperVisible = false
      }
    },
    // 裁剪取消
    cropperClose() {
      this.dialogCropperVisible = false
    },
    async addFileChange(file, fileList) {
      // 上传，拿到file文件
      this.files = file.raw
      this.$nextTick(() => {
        this.optionImg = URL.createObjectURL(file.raw)
        this.fileinfo = file.raw
        this.dialogCropperVisible = true
      })
    },
    // 删除场馆设施已上传图片
    deleteDeviceConfigAddImage() {
      this.$set(this.formAddAccount, 'faceImg2', '')
      this.$set(this.formAddAccount, 'faceImg', '')
    },
    // 获取场馆列表
    getVenueList() {
      venueList({ param: {}}).then((res) => {
        if (res.errorCode !== '000000') return
        this.venueListData = res.recordList
      })
    },
    // 获取角色列表
    getRoleList() {
      roleList({}).then((res) => {
        if (res.errorCode !== '000000') return
        this.roleListData = res.recordList
      })
    },
    // 清空筛选项
    clearFilters() {
      this.filters = {}
      this.getList(1)
    },
    handleSizeChange(value) {
      this.pagination.rows = value
      this.getList(1)
    },
    // 获取账号列表
    getList(page) {
      const { pagination, filters: param } = this
      if (page) {
        pagination.page = page
        this.pagination.page = page
      }
      if (pagination.page === 1) {
        pagination.firstQueryTime = parseTime(new Date())
      }
      this.listLoading = true
      accountList({ pagination, param }).then(res => {
        this.listLoading = false
        if (res.errorCode === '000000') {
          for (const i in res.recordList) {
            const { stadiumList } = res.recordList[i]
            const { roleList } = res.recordList[i]
            res.recordList[i].stadiumList_ = []
            for (const j in stadiumList) {
              res.recordList[i].stadiumList_.push(stadiumList[j].name)
            }
            res.recordList[i].stadiumList_ =
            res.recordList[i].stadiumList_.join('/')

            res.recordList[i].roleList_ = []
            for (const j in roleList) {
              res.recordList[i].roleList_.push(roleList[j].name)
            }
            res.recordList[i].roleList_ = res.recordList[i].roleList_.join('/')
          }
          this.list = res.recordList
          this.total = res.totalCount
        }
      }).catch(() => {
        this.listLoading = false
      })
    },
    change() {
      const { venueListData } = this
      const param = { ...this.formAddAccount }
      param.list = []
      for (const i in venueListData) {
        if (venueListData[i].checked) {
          param.list.push(venueListData[i].id)
        }
      }
      this.$set(this.formAddAccount, 'list', param.list)
    },
    // 重置密码
    toAccountRepassword(row) {
      this.$confirm(`此操作将重置${row.userName}的密码为默认密码，确认吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        accountRepassword({ param: { userId: row.id }}).then((res) => {
          if (res.errorCode !== '000000') return
          this.$message.success('重置密码成功')
        })
      })
    },
    // 启用禁用
    toAccountStatus(status, userId) {
      accountStatus({ param: { status, userId }})
    },
    // 新增 编辑 用户
    toAccountAdd(type, row) {
      this.addEditType = type
      this.showAddAccount = true
      // 编辑 数据回显
      if (row) {
        const { roleList, stadiumList } = row
        // const stadiumList_ = []
        row.roleIds = []
        row.list = []
        for (const item of roleList) {
          row.roleIds.push(String(item.roleId))
        }
        for (const item of stadiumList) {
          row.list.push(item.stadiumId)
        }
        // for (const i in this.venueListData) {
        //   if (stadiumList_.includes(this.venueListData[i].id)) {
        //     this.$set(this.venueListData[i], 'checked', true)
        //   }
        // }
        // this.change()
        this.formAddAccount = { ...row, userNameTemp: row.userName }
        this.$nextTick(() => {
          this.$refs.ruleForm.clearValidate()
        })
      }
    },
    // // 获取角色详情信息
    // getRoleDetail(id) {
    //   getShopUser({ param: { id }}).then((res) => {
    //     this.roleListData = res.recordList
    //   })
    // },
    // 取消 新增 编辑 用户
    cancelAddAccount() {
      for (const item of this.venueListData) {
        item.checked = false
      }
      this.formAddAccount = {
        userName: '',
        realName: '',
        phone: '',
        roleIds: [],
        list: [],
        status: '1',
        info: ''
      }
      this.showAddAccount = false
    },
    // 确认新增 编辑 用户
    confirmAddAccount() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          const { addEditType } = this
          const param = { ...this.formAddAccount }
          this.subLoading = true
          if (addEditType) {
            accountEdit({ param }).then((res) => {
              this.subLoading = false
              if (res.errorCode !== '000000') return
              this.showAddAccount = false
              this.getList(1)
            }, () => {
              this.subLoading = false
            })
          } else {
            accountAdd({ param }).then((res) => {
              this.subLoading = false
              if (res.errorCode !== '000000') return
              this.showAddAccount = false
              this.getList(1)
            }, () => {
              this.subLoading = false
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 删除用户
    toAccountDelete(userId) {
      this.$confirm('此操作将删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          // 删除绑定角色
          accountRoleDelete({ param: { userId }}).then((ress) => {
            if (ress.errorCode !== '000000') return
            // 删除账号
            accountDelete({ param: { id: userId }}).then((resss) => {
              if (resss.errorCode !== '000000') return
              this.$message.success('删除成功')
              this.getList(1)
            })
          })
        })
        .catch(() => {
          // this.$message({
          //   type: 'info',
          //   message: '已取消删除'
          // })
        })
    }
  }
}
</script>
<style lang="scss" scoped>
@import "@/styles/variables.scss";
.device-uploader {
  width: 80px;
  height: 80px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fff;
  cursor: pointer;
  border: 1px dashed #ccc;
  border-radius: 8px;
  transition: all 0.3s;
  margin-right: 20px;
  &:hover {
    border-color: $menuActive;
    .uploader-icon {
      color: $menuActive;
    }
  }
  ::v-deep .el-upload {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;
    .file {
      width: 100%;
      height: 100%;
      position: absolute;
      top: 0;
      left: 0;
      background-size: contain;
      background-position: center;
      background-repeat: no-repeat;
      border-radius: 8px;
      display: flex;
      align-items: center;
      justify-content: center;
      .delete {
        background-color: rgba(0, 0, 0, 0.5);
        position: absolute;
        width: 100%;
        height: 100%;
        top: 0;
        left: 0;
        display: none;
        align-items: center;
        justify-content: center;
        .icon {
          color: #fff;
        }
      }
      &:hover {
        .delete {
          display: flex;
        }
      }
    }
  }
  .uploader-icon {
    color: #aaaaaa;
    font-size: 22px;
    transition: all 0.3s;
  }
}
</style>

